/**
 * MIT License
 *
 * Copyright (C) 2024 Huawei Device Co., Ltd.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

import measure, { MeasureOptions } from '@ohos.measure';
import display from '@ohos.display';
import { text } from "@kit.ArkGraphics2D";

export const getDensity = () => display.getDefaultDisplaySync().densityPixels;

export function config(measureText: MeasureOptions) {
  let textSize = measure.measureTextSize(measureText);
  return textSize;
};

function getWidth(width: number | undefined | null) {
  let densityWidth: number = 0;
  if (width) {
    densityWidth = width;
  } else {
    densityWidth = Math.floor(display.getDefaultDisplaySync().width / display.getDefaultDisplaySync().densityPixels);
  }
  return densityWidth;
}

export function measureTextParagraph(measureOptions: MeasureOptions, width: number) {
  let myTextStyle: text.TextStyle = {
    fontSize: Number(measureOptions.fontSize),
    fontStyle: text.FontStyle.NORMAL,
    letterSpacing: Number(measureOptions.letterSpacing) || 0,
  };
  let myParagraphStyle: text.ParagraphStyle = {
    textStyle: myTextStyle,
  };
  let ParagraphGraphBuilder = new text.ParagraphBuilder(myParagraphStyle, new text.FontCollection());
  ParagraphGraphBuilder.addText(`${measureOptions.textContent}`);
  // 文字绘制
  let paragraph = ParagraphGraphBuilder.build();
  paragraph.layoutSync(getWidth(width));
  // 行数
  let lines = paragraph.getLineCount();
  // 最后一行宽
  let lastLineWidth = paragraph.getLineWidth(lines - 1);
  return {
    lines: lines,
    lastLineWidth: lastLineWidth,
  };
}